// var DEBUGGER = true;
var AUTHORIZER_APPID = 'wx36bea992a3856d4a'; // mofa

var COUPON = '/api/may-promo/promo-coupon';

/* global mayPromoMixin, Vue, weui, axios, Qs */
function initCoupon() {
  return new Vue({

    el: '#shopping',

    mixins: [mayPromoMixin],

    data() {
      return {

        coupon_lists: [],

        openid: '',

        appid: '',

        user_info: null,

        loading: false,

      };
    },


    mounted() {
      var self = this;

      var loading = weui.loading('加载中...');

      this.resolveOpenId()

        .then((openid) => {
          self.openid = openid;

          self.fetchCouponList({

            appid: AUTHORIZER_APPID,

            openid,

          });

          self.fetchUserInfo(openid);
        })

        .then(() => {
          loading.hide();
        });
    },


    methods: {
      /**
       * 颜色类名
       */
      getClassName(discount) {
        var value = parseInt(discount, 10);
        var classObject = {
          purple: false,
          yellow: false,
          blue: false,
          default: false,
        };
        switch (value) {
          case 500:
            classObject.purple = true;
            break;
          case 300:
            classObject.yellow = true;
            break;
          case 200:
            classObject.blue = true;
            break;
          default:
            classObject.blue = true;
            break;
        }
        return classObject;
      },


      /**
       * 获取购物券列表方法
       * @param param
       */
      fetchCouponList(param) {
        var self = this;

        self.loading = true;

        var queryStr = Qs.stringify(param);

        axios.get(`${COUPON}?${queryStr}`)

          .then((response) => {
            if (response.data.code !== 0) {
              throw new Error(response.data.error);
            } else {
              self.coupon_lists = response.data.coupon_lists;
            }
          })

          .catch((error) => {
            console.error(error);
          })

          .then(() => {
            self.loading = false;
          });
      },

      /**
       * 获取使用购物券方法
       */
      patchUseCoupon(code) {
        var self = this;

        weui.confirm('确认使用?', () => {
          var param = {
            _method: 'PUT',
            openid: self.openid,
            appid: AUTHORIZER_APPID,
          };

          axios.post(`${COUPON}/${code}`, param)

            .then((response) => {
              if (response.data.code === 0) {
                weui.toast('使用成功');

                self.fetchCouponList({
                  appid: AUTHORIZER_APPID,
                  openid: self.openid,
                });
              } else {
                throw new Error(response.data.error);
              }
            })

            .catch((error) => {
              console.error(error);
            });
        });
      },
    },
  });
}

initCoupon();
